package com.joney.common.utils;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.joney.common.exception.DefaultException;
import com.joney.common.pojo.UserSession;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxianchen
 * @create 2018-03-01
 * @desc JWT验证器
 */
@Log4j2
public class JwtToken {

    private static final String SECRET_SALT = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";
    private static final String PAYLOAD = "payload";
    //header Base64编码 header变了,此值也会变
    private static final String SECRET_HEADER = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.";
    //过期时间默认240小时，10天
    private static final int EXPIRES_TIME = 240;
    /**
     * @desc 加密，传入一个对象和有效期
     * @author wangxianchen
     * @create 2018-03-01
     * @param jsonPayLoad
     * @return
     * @throws JsonProcessingException
     * @throws UnsupportedEncodingException
     */
    public static  String sign(String jsonPayLoad) throws JsonProcessingException, UnsupportedEncodingException {
        //签发时间
        Date issuedDate = new Date();
        //过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR,EXPIRES_TIME);
        Date expiresDate = nowTime.getTime();
        Map<String,Object> header = new HashMap<String,Object>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        String token = JWT.create()
                .withClaim(PAYLOAD,jsonPayLoad) //payload 负载数据
                .withExpiresAt(expiresDate) //设置过期时间 过期时间大于签发时间
                .withIssuedAt(issuedDate) //设置签发时间
                .sign(Algorithm.HMAC256(SECRET_SALT));
        return token.substring(token.indexOf(".")+1);
    }

    /**
     * @desc 解密，传入一个加密后的token字符串和解密后的类型
     * @author wangxianchen
     * @create 2018-03-01
     * @param token
     * @return
     */
    public static UserSession unsign(String token) throws DefaultException{
        if(token == null){
            log.error("token为空");
            return null;
        }
        DecodedJWT jwt;
        try {
            final JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_SALT)).build();
            jwt = verifier.verify(SECRET_HEADER+token);
        } catch (Exception e) {
            log.error("登录凭证已过期，请重新登录。token={}",token);
            return null;
        }
        return JSON.parseObject(jwt.getClaim(PAYLOAD).asString(),UserSession.class);
    }

    /**
     * 获取当前登录用户
     * @return
     */
    public static UserSession getLoginUser(){
        String token = CookieUtil.getTokenByCookie(getCurrentRequest());
        return JwtToken.unsign(token);
    }

    /**
     * 获取当前登录用户
     * @return
     */
    public static UserSession getLoginUser(HttpServletRequest request){
        String token = CookieUtil.getTokenByCookie(request);
        return JwtToken.unsign(token);
    }
    /**
     * 获取当前登录用户ID
     * @return
     */
    public static Long getLoginUserId(){
        return getLoginUserId(getCurrentRequest());
    }
    /**
     * 获取当前登录用户ID
     * @return
     */
    public static Long getLoginUserId(HttpServletRequest request){
        UserSession userSession = getLoginUser(request);
        return userSession != null ? userSession.getUid() : null;
    }
    /**
     * @desc 获取当前请求request,这个必需在controller中使用
     * @author wangxianchen
     * @create 2018-03-27
     * @return
     */
    private static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static void main(String[] args) {
        try {
            UserSession us = new UserSession();
            us.setUid(1000L);
            us.setUname("rabbit");
            String token = sign(JSON.toJSONString(us));
            System.out.println("token="+token);
            UserSession us2 = unsign(token);
            System.out.println(us2);
        } catch (JsonProcessingException e) {
            log.error("JSON处理异常",e);
        } catch (UnsupportedEncodingException e) {
            log.error("不支持的编码方式",e);
        }
    }
}